<template>
    <div class="photo-form-container">
        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <el-row :gutter="20" style="width: 100%;">
                        <el-col :span="4">
                            <span class="form-title">{{ formTitle }}</span>
                        </el-col>
                        <el-col :span="20">
                            <el-alert v-if="alertMessage" :title="alertMessage" :type="alertType" show-icon
                                :closable="false" />
                        </el-col>
                    </el-row>
                    <!-- <el-button type="primary" @click="submitForm" :loading="submitting">
                        保存
                    </el-button> -->
                </div>
            </template>
            <el-row :gutter="20">
                <el-col :span="6" class="file-tree-container">
                    <FileTree @file-selected="handleFileSelected" />
                </el-col>
                <el-col :span="18">
                    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="right">
                        <!-- 图片路径选择 -->
                        <el-form-item label="图片路径" prop="imagePath">
                            <el-input v-model="formData.imagePath" readonly>
                                <!-- <template #append>
                                    <el-button @click="handleSelectImage">选择图片</el-button>
                                </template> -->
                            </el-input>
                        </el-form-item>

                        <el-row>
                            <el-col :span="12">
                                <!-- <el-form-item label="图片名称" prop="imageName">
                                    <el-input v-model="formData.imageName" />
                                </el-form-item> -->
                                <el-form-item label="图片背景" prop="imageBackground">
                                    <el-input v-model="formData.imageBackground" />
                                </el-form-item>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="拍摄日期" prop="shootingDate">
                                            <el-input v-model="formData.shootingDate" placeholder="格式: YYYYMMDD" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="时间段" prop="shootingPeriod">
                                            <el-input v-model="formData.shootingPeriod" />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-form-item label="拍摄地点" prop="shootingLocation">
                                    <el-input v-model="formData.shootingLocation" />
                                </el-form-item>

                                <el-form-item label="事由" prop="eventReason">
                                    <el-input v-model="formData.eventReason" type="textarea" :rows="3" />
                                </el-form-item>
                                <el-form-item label="图为" prop="picIs">
                                    <el-input v-model="formData.picIs" />
                                </el-form-item>

                                <el-form-item label="单位" prop="organization">
                                    <el-input v-model="formData.organization" />
                                </el-form-item>

                                <el-divider>摄影者信息</el-divider>

                                <div v-for="(person, index) in formData.journalists" :key="index" class="person-item">
                                    <el-row :gutter="20">
                                        <el-col :span="10">
                                            <el-form-item
                                                :label="index === formData.journalists.length - 1 ? '摄影者姓名' : `摄影者${index + 1}`"
                                                :prop="`journalists[${index}].name`">
                                                <el-input v-model="person.name" />
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-button v-if="index === formData.journalists.length - 1" type="primary"
                                                plain @click="addJournalist" :icon="Plus">
                                                添加
                                            </el-button>
                                            <el-button v-else type="danger" plain @click="removeJournalist(index)"
                                                :icon="Delete">
                                                删除
                                            </el-button>
                                        </el-col>
                                    </el-row>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <!-- 图片预览 -->
                                <el-form-item v-if="imagePreview">
                                    <el-image :src="imagePreview" :preview-src-list="[imagePreview]" fit="contain"
                                        style="height: auto; width: auto; max-height: none; max-width: none"
                                        :zoom-rate="1.2" :preview-teleported="true">
                                        <template #error>
                                            <div class="image-slot">
                                                <el-icon>
                                                    <Picture />
                                                </el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                    <div
                                        style="width: 100%; display: flex; justify-content: center; align-items: center;">
                                        <span>{{ formData.imageName }}</span>
                                        <el-button type="text" size="small" @click="copyToClipboard(formData.imageName)"
                                            :icon="CopyDocument" title="复制" />
                                    </div>
                                </el-form-item>
                                <el-form-item>
                                    <el-input v-model="formData.extendedData.originalText" type="textarea" :rows="3" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="图片格式" prop="imageFormat">
                                    <el-input v-model="formData.imageFormat" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="图片大小" prop="imageSize">
                                    <el-input v-model="formData.imageSize" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="图片尺寸" prop="imageScale">
                                    <el-input v-model="formData.imageScale" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="分辨率" prop="imageDpi">
                                    <el-input v-model="formData.imageDpi" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-divider>人物信息</el-divider>

                        <div v-for="(person, index) in formData.persons" :key="index" class="person-item">
                            <el-row :gutter="20">
                                <el-col :span="6">
                                    <el-form-item :label="index === formData.persons.length - 1 ? '人物位置' : ''"
                                        :prop="`persons[${index}].positionInImage`"
                                        :rules="index === formData.persons.length - 1 ? null : personRules.positionInImage">
                                        <el-input v-model="person.positionInImage" placeholder="如: 中1, 左1" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item :label="index === formData.persons.length - 1 ? '姓名' : ''"
                                        :prop="`persons[${index}].name`"
                                        :rules="index === formData.persons.length - 1 ? null : personRules.name">
                                        <el-input v-model="person.name" @change="searchPositionByName(index)" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-form-item :label="index === formData.persons.length - 1 ? '职务' : ''"
                                        :prop="`persons[${index}].position`"
                                        :rules="index === formData.persons.length - 1 ? null : personRules.position">
                                        <el-input v-model="person.position" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-button v-if="index === formData.persons.length - 1" type="primary" plain
                                        @click="addPerson" :icon="Plus">
                                        添加
                                    </el-button>
                                    <el-button v-else type="danger" plain @click="removePerson(index)" :icon="Delete">
                                        删除
                                    </el-button>
                                </el-col>
                            </el-row>
                        </div>

                        <el-divider>题名设置</el-divider>
                        <el-row>
                            <el-col :span="20">
                                <el-form-item label="合成题名" prop="compositeTitle">
                                    <el-input :disabled="isLockCompositeTitle" v-model="formData.compositeTitle"
                                        type="textarea" :rows="3" />
                                    <el-button type="text" size="small"
                                        @click="copyToClipboard(formData.compositeTitle)" title="复制">复制</el-button>
                                    <div class="lock-icon">
                                        <el-tooltip class="box-item" effect="dark"
                                            :content="isLockCompositeTitle ? '当前合成题名已锁定' : '点击锁定当前合成题名，可自动复制到下一页'"
                                            placement="right-end"><el-icon @click="toggleLockStatus"
                                                style="cursor: pointer;">
                                                <Lock style="color:#409eff;" v-if="isLockCompositeTitle" />
                                                <Unlock v-else />
                                            </el-icon></el-tooltip>
                                    </div>
                                </el-form-item>
                                <el-form-item label="图片题名" prop="imageTitle">
                                    <el-input v-model="formData.imageTitle" type="textarea" :rows="3" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-form-item class="form-actions">
                            <!-- <el-button @click="handleReset">清空</el-button> -->
                            <!-- 下一个文件夹的第一张图 -->
                            <el-button @click="handleNextDir">下一件</el-button>
                            <!-- 当前文件夹的下一张图 -->
                            <el-button @click="handleNextPic">下一页</el-button>
                            <el-button type="primary" @click="submitForm">提交</el-button>
                        </el-form-item>
                        <el-form-item label="是否移馆" prop="isMovedToArchive">
                            <el-switch v-model="formData.isMovedToArchive" />
                        </el-form-item>
                        <el-form-item label="档号" prop="fileNumber">
                            <el-input v-model="formData.fileNumber" />
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script setup lang="ts">
defineOptions({
    name: 'NewsPhoto'
})
import { ref, computed, watch } from 'vue'
import { Plus, Delete, Picture, CopyDocument, Position } from '@element-plus/icons-vue'
import { ElMessage, parseDate } from 'element-plus'
import FileTree from '@/components/FileTree.vue'
import { parseArchivePath } from '../utils/parsePath';
import { showAlert } from '@/utils/alert'
import { createNewsPhoto, upload } from '@/api/newsPhotos'
import { searchPersonPosition } from '@/api/personPosition'
import { addPersonPosition } from '@/api/personPosition'
import { getEXIFFromBlob, handleDPIByTags } from '../utils/fileUtil'
// Type definition for file tree entries
interface DirectoryEntry {
    path: string;
    type: 'file' | 'directory';
    children?: DirectoryEntry[];
}

// 提示信息
const alertMessage = ref('')
const alertType = ref<'success' | 'error'>('success')

const selectedFilePath = ref('') // 当前选中的文件路径
const fileTreeData = ref([]) // 当前文件树数据

const isLockCompositeTitle = ref(false)
const curCompositeTitle = ref('')
function toggleLockStatus() {
    isLockCompositeTitle.value = !isLockCompositeTitle.value
    if (isLockCompositeTitle.value) {
        curCompositeTitle.value = formData.value.compositeTitle
    }
    console.log(curCompositeTitle)
}

// 工具函数
const showAlert = (message: string, type: 'success' | 'error') => {
    alertMessage.value = message
    alertType.value = type
    setTimeout(() => {
        alertMessage.value = ''
    }, type === 'error' ? 5000 : 3000)
}

const parsedData = ref();

// 表单数据
const formData = ref({
    imagePath: '',
    imageName: '',
    fileNumber: '',
    compositeTitle: '',
    imageBackground: '', // 添加图片背景属性
    imageTitle: '',
    shootingDate: '',
    shootingPeriod: '',
    shootingLocation: '',
    eventReason: '',
    organization: '',
    imageFormat: '',
    imageScale: '', // 添加图片尺寸属性
    imageSize: '',  // 添加图片大小属性（如果未定义）
    imageDpi: '',   // 添加分辨率属性（如果未定义）
    isMovedToArchive: false,
    persons: [{ positionInImage: '', name: '', position: '' }],
    journalists: [{ name: '' }],
    picIs: '',
    extendedData: {
        originalText: '',
        persons: []
    }
})

// 监听相关字段的变化
watch(
    () => [
        formData.value.shootingDate,
        formData.value.shootingPeriod,
        formData.value.persons,
        formData.value.shootingLocation,
        formData.value.eventReason,
        formData.value.picIs,
        formData.value.organization,
        formData.value.journalists
    ],
    () => {
        if (!isLockCompositeTitle.value) {
            formData.value.compositeTitle = concatTitle();
        } else {
            formData.value.compositeTitle = replacePictureDescription(formData.value.compositeTitle, formData.value.picIs)
        }
    },
    { deep: true }
);


// 图片预览
const imagePreview = ref('')

// 表单引用
const formRef = ref(null)
const submitting = ref(false)

// 计算标题
const formTitle = computed(() => {
    return formData.value.imageName ? `编辑: ${formData.value.imageName}` : '新增照片信息'
})

const handleFileInfo = async (fullPath: string) => {
    if (!fullPath) return

    // 设置表单数据
    formData.value.imagePath = fullPath
    const fileName = fullPath.split(/[\\/]/).pop()
    formData.value.imageName = (fileName ?? '').replace(/\.[^/.]+$/, '')
    const format = fullPath.split('.').pop();
    formData.value.imageFormat = format ? format.toUpperCase() : '';


    // 生成预览
    const buffer = await window.electronAPI.readFile(fullPath)
    const blob = new Blob([buffer])

    getImageInfo(blob)

    parsePath(fullPath);

}

function getImageInfo(blob) {
    getEXIFFromBlob(blob)
        .then(exifTags => {
            const { dpiX, dpiY } = handleDPIByTags(exifTags);
            formData.value.imageDpi = dpiX === dpiY ? dpiX : `${dpiX}*${dpiY}`;
        });
    const url = imagePreview.value = URL.createObjectURL(blob)
    const fileSizeInKB = (blob.size / 1024).toFixed(2); // 转为KB并保留2位小数
    return new Promise((resolve) => {
        const img = new Image();

        img.onload = () => {
            resolve({
                width: img.naturalWidth,  // 实际宽度（像素）
                height: img.naturalHeight, // 实际高度（像素）
                size: fileSizeInKB, // 文件大小（KB）
            });
            formData.value.imageScale = `${img.naturalWidth}x${img.naturalHeight}`; // 设置图片尺寸
            formData.value.imageSize = `${fileSizeInKB} KB`; // 设置图片大小
        };

        img.src = url;
    });
}


// 表单提交
const submitForm = async () => {
    try {
        submitting.value = true
        await formRef?.value?.validate()
        // 这里替换为实际的保存逻辑
        const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
        const operatorId = userInfo.value.userId || null
        if (!operatorId) {
            ElMessage.error('操作员信息未找到，请先登录')
            return
        }
        // 更新姓名职务表
        const persons: any = [];
        formData.value.persons.forEach(item => {
            const { name, position } = item;
            if (!name || !position) return;
            const data = handlePersonPositionData(item);
            persons.push(data);
            savePersonPosition(data);
        })
        formData.value.extendedData.persons = persons;
        const postData = {
            ...formData.value,
            journalists: formData.value.journalists.map(item => item.name).join(','),
            extendedData: JSON.stringify(formData.value.extendedData)
        }
        console.log('提交数据:', postData)
        const result = await createNewsPhoto(postData, operatorId)
        if (result) {
            ElMessage.success('保存成功')
        } else {
            ElMessage.error('保存失败:' + result)
        }
        // 图片入库
        saveImgToArchive(postData.imagePath, postData.imageName, formData.value.imageFormat)
    } catch (error) {
        console.error('表单验证失败:', error)
    } finally {
        submitting.value = false
    }
}

// 重置表单
const handleReset = () => {
    formRef.value?.resetFields()
    setCompositeTitle();
    imagePreview.value = ''
    formData.value.persons = [{ positionInImage: '', name: '', position: '' }]
    formData.value.journalists = [{ name: '' }]
}

// 添加/删除人物
const addPerson = () => {
    formData.value.persons.push({ positionInImage: '', name: '', position: '' })
    const persons = formData.value.persons
    if (persons.length <= 1) return;
    const lastPerson = persons[persons.length - 2];
    const postData = handlePersonPositionData(lastPerson);
    savePersonPosition(postData)
}

function handlePersonPositionData(person) {
    const { name, position } = person;
    if (!name || !position) return;
    const postData = {
        personName: name,
        positionTitles: position ? position.split(/[ 、]+/) : []
    }
    return postData;
}

const savePersonPosition = async (data: any) => {
    if (!data) return;
    // 调用接口保存到姓名职务表
    console.log('请求参数', data);
    await addPersonPosition(data);
}

const removePerson = (index) => {
    formData.value.persons.splice(index, 1)
}

const addJournalist = () => {
    formData.value.journalists.push({ name: '' })
}

const removeJournalist = (index) => {
    formData.value.journalists.splice(index, 1)
}

// 验证规则
const rules = {
    imagePath: [{ required: true, message: '请选择图片', trigger: 'blur' }],
    // imageName: [{ required: true, message: '请输入图片名称', trigger: 'blur' }],
    shootingDate: [{ required: true, message: '请选择拍摄日期', trigger: 'change' }]
}

const personRules = {
    positionInImage: [{ required: true, message: '请输入人物位置', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    position: [{ required: true, message: '请输入职务', trigger: 'blur' }]
}

const handleFileSelected = (file: any) => {
    fileTreeData.value = file.fileTree || fileTreeData.value
    selectedFilePath.value = file.path
    const fullPath = file.path
    const SUPPORTED_EXTS = new Set([
        '.jpg', '.jpeg', '.png', '.gif', '.bmp',
        '.tif', '.tiff', '.webp', '.heic', '.heif'
    ]);
    const ext = file.path.split('.').pop()?.toLowerCase() || '';

    if (SUPPORTED_EXTS.has('.' + ext)) {
        // 清空表单
        handleReset()
        handleFileInfo(fullPath)
        handleExifData(file.exif)
    } else {
        const normalizedPath = fullPath.replace(/\\/g, '/');
        window.electronAPI.openFile(normalizedPath)
    }
}

function handleExifData(exifData: any) {
    if (!exifData) return;
    console.log('EXIF Data:', exifData, exifData.XResolution, exifData.YResolution);
}

function parseDateToChineseWithValidation(dateStr: string) {
    // 检查输入是否为8位数字
    if (!/^\d{8}$/.test(dateStr)) {
        return "";
    }

    // 提取年、月、日部分
    const year = parseInt(dateStr.substring(0, 4));
    const month = parseInt(dateStr.substring(4, 6));
    const day = parseInt(dateStr.substring(6, 8));

    // 验证日期有效性
    const date = new Date(year, month - 1, day);
    if (date.getFullYear() !== year ||
        date.getMonth() + 1 !== month ||
        date.getDate() !== day) {
        return "输入的日期无效，请检查";
    }

    // 格式化为两位数月份和日期
    const formattedMonth = month.toString().replace(/^0/, '');
    const formattedDay = day.toString().replace(/^0/, '');

    return `${year}年${formattedMonth}月${formattedDay}日`;
}
function convertTimeToPeriod(time24: string) {
    // 提取小时部分
    const hour = parseInt(time24.split(':')[0]);
    if (isNaN(hour) || hour < 0 || hour > 23) {
        return '';
    }
    if (hour >= 5 && hour < 12) {
        return '上午';
    } else if (hour >= 12 && hour < 18) {
        return '下午';
    } else if (hour >= 18 && hour < 24) {
        return '晚上';
    } else {
        return '凌晨';
    }
}

// 合成题名={时间+（时间段）中间用“，”隔开}+人物（多个人物中间用“、”隔开，人物这间的位置用“（）”）+地点+事由+图为（图为内容要加（））+单位+摄影者（多个摄影都中间用空格隔开）+摄字（单位 摄影者 摄 三者之间用空格隔开）
function concatTitle(): string {
    const date = parseDateToChineseWithValidation(formData.value.shootingDate) + convertTimeToPeriod(formData.value.shootingPeriod);
    const personStr = formData.value.persons.filter(item => item.name)
        .map(item => item.position + item.name + (item.positionInImage ? ('(' + item.positionInImage + ')') : '')).join('、');
    const location = formData.value.shootingLocation ? ('在' + formData.value.shootingLocation + '，') : '';
    const eventReason = formData.value.eventReason + '。';
    const picStr = formData.value.picIs ? `（图为${formData.value.picIs}）` : '';
    const journalistStr = formData.value.organization + ' ' + formData.value.journalists.map(item => item.name).join(' ')
    const takeOperation = journalistStr.trim() ? ' 摄' : '';
    return date + personStr + location + eventReason + picStr + journalistStr + takeOperation;
}

function setCompositeTitle() {
    if (isLockCompositeTitle.value) {
        formData.value.compositeTitle = replacePictureDescription(curCompositeTitle.value, formData.value.picIs)
    } else {
        formData.value.compositeTitle = concatTitle();
    }
}

function replacePictureDescription(text: string, picIs: string) {
    // 使用正则表达式匹配 "(图为xxx)" 格式
    const pattern = /（图为([^）]*)）/g;

    // 替换匹配到的内容
    return text.replace(pattern, `（图为${picIs}）`);
}

const parsePath = (fullPath: string) => {
    try {
        parsedData.value = parseArchivePath(fullPath);
        if (!parsedData || !parsedData.value) return;
        console.log('Parsed Data:', parsedData.value);
        if (!parsedData.value.year || !parsedData.value.month || !parsedData.value.fileDate) {
            showAlert('路径格式不正确，无法正确解析年、月或日期', 'error');
        }
        formData.value.shootingDate = `${parsedData.value.year}${parsedData.value.month.padStart(2, '0')}${parsedData.value.fileDate.replace('.', '').padStart(2, '0')}`;
    } catch (error) {
        showAlert('解析出错：' + error.message, 'error');
    }
};

function handleNextPic() {
    if (!selectedFilePath.value || !fileTreeData.value?.length) return;

    // 1. 扁平化文件树，便于查找
    const flatFiles = flattenTree(fileTreeData.value);

    // 2. 找到当前选中文件的索引
    const currentIndex = flatFiles.findIndex(file => file.path === selectedFilePath.value);

    if (currentIndex === -1) return;

    // 3. 查找下一个文件（跳过文件夹）
    let nextIndex = currentIndex + 1;
    while (nextIndex < flatFiles.length) {
        const nextFile = flatFiles[nextIndex];
        if (nextFile.type === 'file') {
            // 找到下一个文件，触发选择
            handleFileSelected(nextFile)
            return;
        }
        nextIndex++;
    }

    // 如果后面没有文件了，可以循环到第一个或给出提示
    ElMessage.primary(`已是最后一个文件`);

}

// 辅助函数：递归扁平化树结构
function flattenTree(tree: DirectoryEntry[]): DirectoryEntry[] {
    const result: DirectoryEntry[] = [];

    tree.forEach(node => {
        result.push(node);
        if (node.children && node.children.length > 0) {
            result.push(...flattenTree(node.children));
        }
    });

    return result;
}


function handleNextDir() {
    if (!selectedFilePath.value || !fileTreeData.value?.length) return;

    // 1. 扁平化文件树，便于查找
    const flatFiles = flattenTree(fileTreeData.value);

    // 2. 找到当前选中文件的索引
    const currentIndex = flatFiles.findIndex(file => file.path === selectedFilePath.value);

    if (currentIndex === -1) return;

    // 3. 查找下一个目录
    let nextIndex = currentIndex + 1;
    while (nextIndex < flatFiles.length) {
        const nextFile = flatFiles[nextIndex];
        if (nextFile.type === 'file' && !isSameDirectory(nextFile.path, selectedFilePath.value)) {
            // 找到下一个目录，触发选择
            handleFileSelected(nextFile)
            return;
        }
        nextIndex++;
    }

    // 如果后面没有目录了，可以循环到第一个或给出提示
    ElMessage.primary(`已是最后一个目录`);
}

function isSameDirectory(filePath1: string, filePath2: string) {
    // 标准化路径分隔符（兼容 Windows 和 Unix）
    const normalizePath = (p) => p.replace(/\\/g, '/');
    const dir1 = normalizePath(filePath1).split('/').slice(0, -1).join('/');
    const dir2 = normalizePath(filePath2).split('/').slice(0, -1).join('/');
    return dir1 === dir2;
}

const copyToClipboard = (text: string) => {
    if (!text) {
        ElMessage.warning('没有内容可复制')
        return
    }

    navigator.clipboard.writeText(text)
        .then(() => {
            ElMessage.success('复制成功')
        })
        .catch(() => {
            ElMessage.error('复制失败，请手动复制')
        })
}

const saveImgToArchive = async (imagePath: string, imageName: string, imageType: string) => {
    const buffer = await window.electronAPI.readFile(imagePath)
    const blob = new Blob([buffer])
    const file = new File([blob], imageName + '.' + imageType, { type: blob.type })
    const postData: any = new FormData()
    postData.append('file', file)
    postData.append('fileName', imageName + '.' + imageType)
    const pathInfo = parseArchivePath(imagePath)
    postData.append('path', pathInfo.year + '/' + pathInfo.month + '/' + pathInfo.fileDate.replace('.', '') + '/' + pathInfo.title)
    const result = await upload(postData)
    if (result) {
        ElMessage.success('图片上传成功')
        handleReset() // 提交成功后重置表单
        handleNextPic() // 自动跳转到下一张图片
    } else {
        ElMessage.error('图片上传失败')
    }
}

const searchPositionByName = async (index: number) => {
    const name = formData.value.persons[index].name;
    if (name) {
        const result = await searchPersonPosition({ name });
        formData.value.persons[index].position = result.map(item => item.positionTitles).join('、');
    }
}
</script>

<style scoped>
.photo-form-container {
    padding: 20px;
}

.form-card {
    /* max-width: 1000px; */
    margin: 0 auto;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.form-title {
    font-size: 18px;
    font-weight: bold;
}

.person-item {
    margin-bottom: 16px;
}

.form-actions {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}

.image-slot .el-icon {
    font-size: 30px;
}

.file-tree-container {
    height: 100vh;
    /* 视口高度 */
    overflow: auto;
    /* 垂直滚动 */
    padding-right: 8px;
    /* 防止滚动条遮挡内容 */
}

.lock-icon {
    position: absolute;
    right: -22px;
    top: 15px;
}

/* 整个滚动条 */
::-webkit-scrollbar {
    width: 5px;
    /* 滚动条的宽度 */
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
    background: #fff;
    /* 轨道颜色 */
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
    background: #eee;
    /* 滑块颜色 */
    border-radius: 10px;
    /* 滑块圆角 */
}

/* 滑块悬停状态 */
::-webkit-scrollbar-thumb:hover {
    background: #555;
    /* 滑块悬停颜色 */
    cursor: pointer;
}
</style>